package com.tianyac.property.controller;

import com.alibaba.fastjson.JSONObject;
import com.tianyac.property.util.IdWorker;
import com.tianyac.property.util.Result;
import com.tianyac.property.util.ResultUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

//    文件上传
    @PostMapping("/upload")
    public Result upload(@RequestParam MultipartFile file){
        //        设置过程数据
        JSONObject processData = new JSONObject();
        try{
            // 如果文件不为空，写入上传路径
            if(!file.isEmpty()){
                // 定义上传文件路径
                String path = "D:\\FileService";
                IdWorker idWorker = new IdWorker();
                // 上传文件名
                String filename = idWorker.worker() + "-" + file.getOriginalFilename();
                processData.put("filename",filename);
                processData.put("filepath","/file/download?fileName="+filename);
                File filepath = new File(path,filename);
//                System.out.println(UUID.randomUUID().toString());
                // 判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }
                // 将上传文件保存到一个目标文件当中
                file.transferTo(new File(path+File.separator+ filename));
                return ResultUtil.success(processData);
            }else{
                return ResultUtil.error(0,"file is null");
            }
        }
        catch (IOException e){
            e.printStackTrace();
            return ResultUtil.error(0,"upload error");
        }
    }

//    文件下载
    @GetMapping("/download")
    public ResponseEntity<byte[]> downLoad(@RequestParam String fileName){
        try{
            // 定义下载文件路径
            String path = "D:\\FileService";
            // 获得要下载文件的File对象
            File file = new File(path+File.separator+ fileName);
            // 创建springframework的HttpHeaders对象
            HttpHeaders headers = new HttpHeaders();
            // 下载显示的文件名，解决中文名称乱码问题
            String downloadFielName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");
            // 通知浏览器以attachment（下载方式）打开图片
            headers.setContentDispositionFormData("attachment", downloadFielName);
            // application/octet-stream ： 二进制流数据（最常见的文件下载）。
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 201 HttpStatus.CREATED
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
        }
        catch (Exception e){
            return null;
        }
    }
}
